<template>
  <div class="login-form">
    <!-- 登录方式切换 -->
    <div class="login-type-switch">
      <a-radio-group v-model:value="loginType" button-style="solid">
        <a-radio-button value="password">密码登录</a-radio-button>
        <a-radio-button value="sms">验证码登录</a-radio-button>
      </a-radio-group>
    </div>

    <a-form
      :model="form"
      :rules="rules"
      @finish="handleLogin"
      layout="vertical"
    >
      <a-form-item label="手机号" name="username">
        <a-input
          v-model:value="form.username"
          placeholder="请输入手机号"
          size="large"
        />
      </a-form-item>

      <!-- 密码登录 -->
      <template v-if="loginType === 'password'">
        <a-form-item label="密码" name="password">
          <a-input-password
            v-model:value="form.password"
            placeholder="请输入密码"
            size="large"
          />
        </a-form-item>
      </template>

      <!-- 验证码登录 -->
      <template v-if="loginType === 'sms'">
        <a-form-item label="验证码" name="code">
          <div class="code-input-group">
            <a-input
              v-model:value="form.code"
              placeholder="请输入验证码"
              size="large"
              style="flex: 1;"
            />
            <a-button
              type="primary"
              size="large"
              :loading="sendingCode"
              :disabled="!form.username || countdown > 0"
              @click="sendCode"
              style="margin-left: 8px;"
            >
              {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
            </a-button>
          </div>
        </a-form-item>
      </template>

      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          :loading="loading"
          size="large"
          block
        >
          登录
        </a-button>
      </a-form-item>

      <a-form-item>
        <div class="form-footer">
          <div class="form-footer-top">
            <span>还没有账号？</span>
            <a @click="$emit('switch-to-register')">立即注册</a>
          </div>
          <div class="form-footer-bottom">
            <a @click="showForgotPassword = true">忘记密码？</a>
          </div>
        </div>
      </a-form-item>
    </a-form>

    <!-- 忘记密码弹窗 -->
    <a-modal
      v-model:open="showForgotPassword"
      title="忘记密码"
      @ok="handleForgotPassword"
      @cancel="showForgotPassword = false"
      :confirm-loading="forgotPasswordLoading"
    >
      <a-form
        :model="forgotPasswordForm"
        :rules="forgotPasswordRules"
        ref="forgotPasswordFormRef"
        layout="vertical"
      >
        <a-form-item label="手机号" name="phone">
          <a-input
            v-model:value="forgotPasswordForm.phone"
            placeholder="请输入手机号"
            size="large"
          />
        </a-form-item>

        <a-form-item label="验证码" name="code">
          <div class="code-input-group">
            <a-input
              v-model:value="forgotPasswordForm.code"
              placeholder="请输入验证码"
              size="large"
              style="flex: 1;"
            />
            <a-button
              type="primary"
              size="large"
              :loading="sendingForgotCode"
              :disabled="!forgotPasswordForm.phone || forgotCountdown > 0"
              @click="sendForgotCode"
              style="margin-left: 8px;"
            >
              {{ forgotCountdown > 0 ? `${forgotCountdown}s` : '获取验证码' }}
            </a-button>
          </div>
        </a-form-item>

        <a-form-item label="新密码" name="newPassword">
          <a-input-password
            v-model:value="forgotPasswordForm.newPassword"
            placeholder="请输入新密码"
            size="large"
          />
        </a-form-item>

        <a-form-item label="确认密码" name="confirmPassword">
          <a-input-password
            v-model:value="forgotPasswordForm.confirmPassword"
            placeholder="请再次输入新密码"
            size="large"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import authAPI from '~/api/auth'

// 定义emit
const emit = defineEmits(['success', 'switch-to-register'])

// 登录方式
const loginType = ref('password')

// 表单数据
const form = reactive({
  username: '',
  password: '',
  code: '',
  loginType: 'password'
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ],
  password: [
    { 
      required: true, 
      message: '请输入密码',
      validator: (rule, value) => {
        if (loginType.value === 'password' && !value) {
          return Promise.reject('请输入密码')
        }
        return Promise.resolve()
      }
    },
    { min: 6, message: '密码至少6个字符' }
  ],
  code: [
    { 
      required: true, 
      message: '请输入验证码',
      validator: (rule, value) => {
        if (loginType.value === 'sms' && !value) {
          return Promise.reject('请输入验证码')
        }
        return Promise.resolve()
      }
    },
    { pattern: /^\d{4,6}$/, message: '验证码格式不正确' }
  ]
}

// 忘记密码相关
const showForgotPassword = ref(false)
const forgotPasswordLoading = ref(false)
const forgotPasswordFormRef = ref()

const forgotPasswordForm = reactive({
  phone: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const forgotPasswordRules = {
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ],
  code: [
    { required: true, message: '请输入验证码' },
    { pattern: /^\d{4,6}$/, message: '验证码格式不正确' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { min: 6, message: '密码至少6个字符' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码' },
    {
      validator: (rule, value) => {
        if (value !== forgotPasswordForm.newPassword) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      }
    }
  ]
}

// 加载状态
const loading = ref(false)
const sendingCode = ref(false)
const sendingForgotCode = ref(false)
const countdown = ref(0)
const forgotCountdown = ref(0)
let countdownTimer = null
let forgotCountdownTimer = null

// 发送登录验证码
const sendCode = async () => {
  if (!form.username) {
    message.error('请先输入手机号')
    return
  }
  
  sendingCode.value = true
  try {
    const response = await authAPI.sendSmsCode({
      phone: form.username,
      scene: 'login'
    })
    
    if (response.status === 'success') {
      message.success('验证码已发送')
      startCountdown()
    } else {
      message.error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    message.error(error.response?.data?.message || '发送失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

// 发送忘记密码验证码
const sendForgotCode = async () => {
  if (!forgotPasswordForm.phone) {
    message.error('请先输入手机号')
    return
  }
  
  sendingForgotCode.value = true
  try {
    const response = await authAPI.sendSmsCode({
      phone: forgotPasswordForm.phone,
      scene: 'reset_password'
    })
    
    if (response.status === 'success') {
      message.success('验证码已发送')
      startForgotCountdown()
    } else {
      message.error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    message.error(error.response?.data?.message || '发送失败，请稍后重试')
  } finally {
    sendingForgotCode.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
  }, 1000)
}

const startForgotCountdown = () => {
  forgotCountdown.value = 60
  forgotCountdownTimer = setInterval(() => {
    forgotCountdown.value--
    if (forgotCountdown.value <= 0) {
      clearInterval(forgotCountdownTimer)
      forgotCountdownTimer = null
    }
  }, 1000)
}

// 处理登录
const handleLogin = async (values) => {
  loading.value = true
  try {
    const loginData = {
      username: form.username,
      loginType: loginType.value
    }
    
    if (loginType.value === 'password') {
      loginData.password = form.password
    } else {
      loginData.code = form.code
    }
    
    const data = await authAPI.login(loginData)
    if (data.code === 200) {
      message.success('登录成功')
      useUserStore().setUserInfo(data.data.user)
      localStorage.setItem('user', JSON.stringify(data.data.user))
      localStorage.setItem('token', data.data.token)
      emit('success')
    } else {
      message.error(data.message || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    message.error(error.response?.data?.message || '网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理忘记密码
const handleForgotPassword = async () => {
  try {
    await forgotPasswordFormRef.value.validate()
    forgotPasswordLoading.value = true
    
    const data = await authAPI.forgotPassword({
      phone: forgotPasswordForm.phone,
      code: forgotPasswordForm.code,
      newPassword: forgotPasswordForm.newPassword
    })
    
    if (data.status === 'success') {
      message.success('密码重置成功')
      showForgotPassword.value = false
      // 清空表单
      Object.assign(forgotPasswordForm, {
        phone: '',
        code: '',
        newPassword: '',
        confirmPassword: ''
      })
    } else {
      message.error(data.message || '密码重置失败')
    }
  } catch (error) {
    console.error('忘记密码错误:', error)
    message.error(error.response?.data?.message || '密码重置失败，请稍后重试')
  } finally {
    forgotPasswordLoading.value = false
  }
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
  if (forgotCountdownTimer) {
    clearInterval(forgotCountdownTimer)
    forgotCountdownTimer = null
  }
})
</script>

<style scoped lang="scss">
.login-form {
  .login-type-switch {
    text-align: center;
    margin-bottom: 24px;
  }
  
  .code-input-group {
    display: flex;
    align-items: center;
  }
  
  .form-footer {
    text-align: center;
    
    .form-footer-top {
      margin-bottom: 8px;
    }
    
    .form-footer-bottom {
      a {
        color: #1890ff;
        cursor: pointer;
        font-size: 14px;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
    
    a {
      color: #1890ff;
      cursor: pointer;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
}

// 确保弹窗中的验证码输入框样式也生效
:deep(.code-input-group) {
  display: flex;
  align-items: center;
}
</style> 